<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Models\User;
use App\Models\Order;
use App\Http\Resources\Front\Order as OrderResource;
use App\Http\Resources\Front\OrderCollection;
use App\Http\Resources\Front\User as UserResource;
use App\Http\Controllers\ApiController;
use Illuminate\Validation\Rule;
use App\Models\UserAddress;
use App\Models\Product;
use App\Models\Shop;
use App\Models\Manager;
use Validator;

class MemberController extends ApiController
{

    /**
     * 会员中心首页
     */
    public function index() {
        $user = Auth::user();
        $shop = $user->shop;
        return view('front.member.index', compact('user', 'shop'));
    }

    /**
     * 用户信息
     */
    public function userInfo() {
        return $this->success(new UserResource(Auth::user()));
    }

    /**
     * 订单
     */
    public function order() {
        return view('front.member.order');
    }

    /**
     * 获取订单列表
     */
    public function fetchOrderList(Request $request)
    {
        $limit = $request->input('size', 10);
        $status = $request->input('status', 'all');

        $orderOrm = Order::orderBy('id', 'DESC')->with(['user' => function($query) {
            $query->select('id', 'name'); // 用户ID，名称
        }])->with(['store' => function($query) {
            $query->select('id', 'name'); // 店铺ID，名称
        }]);

        if($status && $status !== 'all') {
            $orderOrm->where('status', Order::getOrderStatus($status));
        }

        return new OrderCollection($orderOrm->paginate($limit));
    }

    /**
     * 获取自定订单
     */
    public function orderShow($id)
    {
        return view('front.member.orderShow', compact('id'));
    }

    /**
     * 获取自定订单
     */
    public function orderSoldShow($id)
    {
        return view('front.member.soldShow', compact('id'));
    }

    /**
     * 我的店铺
     */
    public function mstore()
    {
        $user = Auth::user();
        $shop = $user->shop;
        if ($shop) {
            // 如何已经有店铺就直接获取商品
            $products = $shop->products;
        } else {
            // 检查是否验证了手机号码
            if (empty(Auth()->user()->telphone)) {
                session(['http_referer' => route('shopping.checkOut')]);
                return redirect()->route('public.phoneVerification'); // 跳转验证号码
            }

            $store = new Shop();
            $store->user_id = $user->id;
            $store->name = $user->name;
            $store->tel = $user->telphone;
            $store->profile = '';
            $store->address = $user->address;
            $store->check = 0;
            $store->type = 0;
            $store->save();
        }

        return view('front.member.store', compact('shop', 'products', 'user'));
    }

    /**
     *  已发布的商品
     */
    public function mstoreProduct(Request $request)
    {
        $limit = $request->input('size', 15);
        $shop = $request->user()->shop;
        
        // 有店铺
        if ($shop) {
            $products = $shop->products()->orderBy('id','DESC');
        } else {
            $products = [];
        }

        $products = $products->paginate($limit);
        foreach($products as &$prod) {
            $prod->friend_date = friendDate($prod->created_at->getTimestamp());
        }

        return $this->success($products);
    }

    /**
     * 添加新商品
     */
    public function mstoreProductCreate() {
        $user = Auth::user();
        if (empty($user->telphone)){
            return redirect()->route('public.phoneVerification');
        }
        
        return view('front.member.productCreate');
    }

    /**
     * 添加新商品
     */
    public function mstoreProductStore(Request $request)
    {
        $messages = [
            'product_name.required' => '名称不能为空',
            'product_pics.required' => '封面图片不能为空',
            'product_price.required' => '价格不能为空',
            'product_unit.required' => '单位不能为空'
        ];

        $validator = Validator::make($request->all(), [
            'product_name' => 'required',
            'product_pics' => 'required',
            'product_price' => 'required',
            'product_unit' =>  'required',
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $user = Auth::user();

        $prodPics = $request->input('product_pics');

        $product = new Product();
        $product->store_id = $user->shop->id; // 自营店store_id为0
        $product->name = $request->input('product_name');
        $product->price = number_format($request->input('product_price'), 2, '.', '');
        $product->unit = $request->input('product_unit');
        $product->info = $request->input('product_description');
        $product->description = $request->input('product_description');
        $product->cover_image = $prodPics[0];
        $product->pic_group = $prodPics;
        $product->spec = $request->input('product_spec'); // 规格
        $product->logistics_mode = json_encode($request->input('product_logistics')); // 支持的物流方式
        $product->address = $request->input('product_address');
        $product->cate_id = $request->input('cate_id');
        $product->status = 1;
        $product->save();

        if(!$product){
            return $this->failed('商品创建失败');
        }else {
            return $this->message('商品创建成功');
        }
    }

    /**
     * 编辑货品
     */
    public function mstoreProductEdit($id, Request $request) {
        return view('front.member.productEdit', compact('id'));
    }

    /**
     * 删除商品
     */
    public function mstoreProductDestory($id) {
        if (!Auth()->user()->mstore) {
            // 连店铺删除个屁
            return $this->failed("更新出错");
        }

        $product = Product::find($id);

        if($product->store->id !== Auth()->user()->mstore->id) {
            // 不是自己发布的商品没有权限更新
            return $this->failed("更新出错");
        }

        if ($product->delete()) {
            return $this->message('删除成功');
        } else {
            return $this->failed('删除失败');
        }
    }

    /**
     * 商品预览
     */
    public function mstoreProductPreview($id , Request $request)
    {
        // 商品详情
        $product =  Product::with(['shop'])->find($id);

        // 店铺信息
        $shop = Shop::with('user')->find($product->shop_id);

        if ($shop->user->id !== $request->user()->id) {
            return redirect()->route('404');
        }
        
        return view('front.member.productPreview', compact('product', 'shop'));
    }

    /**
     * 更新商品
     */
    public function mstoreProductUpdate($id , Request $request) {
        $messages = [
            'product_name.required' => '名称不能为空',
            'product_pics.required' => '封面图片不能为空',
            'product_price.required' => '价格不能为空',
            'product_unit.required' => '单位不能为空'
        ];

        $validator = Validator::make($request->all(), [
            'product_name' => 'required',
            'product_pics' => 'required',
            'product_price' => 'required',
            'product_unit' =>  'required',
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $user = Auth::user();

        $prodPics = $request->input('product_pics');

        $product = Product::find($id);

        if($product->store->id !== $request->user()->mstore->id) {
            // 不是自己发布的商品没有权限更新
            return $this->failed("更新出错");
        }

        $product->store_id = $user->mstore->id; // 自营店store_id为0
        $product->name = $request->input('product_name');
        $product->price = number_format($request->input('product_price'), 2, '.', '');
        $product->unit = $request->input('product_unit');
        $product->info = $request->input('product_description');
        $product->description = $request->input('product_description');
        $product->cover_image = $prodPics[0];
        $product->pic_group = $prodPics;
        $product->spec = $request->input('product_spec'); // 规格
        $product->logistics_mode = json_encode($request->input('product_logistics')); // 支持的物流方式
        $product->address = $request->input('product_address');
        $product->cate_id = $request->input('cate_id');
        $product->status = 1;
        $product->save();

        if(!$product){
            return $this->failed('商品更新失败');
        }else {
            return $this->message('商品更新成功');
        }
    }

    /**
     * 订单
     */
    public function sold() {
        return view('front.member.sold');
    }

    /**
     * 我的地址
     */
    public function address($action = null, Request $request) {
        return view('front.member.address', compact('action'));
    }


    /**
     * 我的银行卡
     */
    public function bankCard() {
        return view('front.member.bankCard');
    }

    /**
     * 保存银行卡信息
     */
    public function bankCardStore(Request $request) {
        $user = Auth()->user();

        if ($user->check !== 2) {
            return $this->failed('请完成实名认证');
        }

        if ($user->bank_card) {
            return $this->failed('银行卡已经绑定');
        }

        $bankCard = $request->input('bank_card');

        $messages = [
            'bank_card.required' => '请输入银行卡',
        ];

        $validator = Validator::make($request->all(), [
            'bank_card' => 'required|min:16|max:19',
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        if (!is_numeric($bankCard)) {
            return $this->failed('卡号必须是数字');
        }

        if (strlen($bankCard) !== 16 && strlen($bankCard) !== 19) {
            return $this->failed('请输入16或19位银行卡号');
        }

        $user->bank_card = $bankCard;
        $user->save();

        return $this->message('银行卡绑定成功');

    }

    /**
     * 删除银行卡
     */
    public function bankCardDestroy() {
        $user = Auth()->user();
        $user->bank_card = '';
        $user->save();
        return $this->message('银行卡删除成功');
    }

    /**
     * 我的认证
     */
    public function certification() {
        $user = Auth()->user();
        return view('front.member.certification', compact('user'));
    }

    /**
     * 个人认证
     */
    public function personalCert()
    {
        return view('front.member.personalCert');
    }

    /**
     * 保存个人认证信息
     */
    public function personalCertStore(Request $request) {
        $messages = [
            'realname.required' => '姓名不能为空',
            'id_card.required' => '身份证号不能为空'
        ];

        $validator = Validator::make($request->all(), [
            'realname' => 'required',
            'id_card' => 'required'
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $user = $request->user();

        if (!in_array($user->check, [-1, 0])) {
            return $this->failed('保存失败');
        }

        $user->realname = $request->input('realname');
        $user->idcard = $request->input('id_card');
        $user->check = 1;
        
        if ($user->save()) {
            return $this->message('提交成功');
        } else {
            return $this->failed('保存失败，请稍后重试');
        }
    }


    /**
     * 企业认证
     */
    public function enterpriseCert()
    {
        return view('front.member.enterpriseCert');
    }

    /**
     * 保存企业验证信息
     */
    public function enterpriseCertStore(Request $request)
    {
        $messages = [
            'idcard_pic.required' => '请上传身份证照',
            'biz_lic_pic.required' => '请上传营业执照'
        ];

        $validator = Validator::make($request->all(), [
            'idcard_pic' => 'required',
            'biz_lic_pic' => 'required'
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $user = $request->user();

        if (!in_array($user->ent_check, [-1, 0])) {
            return $this->failed('保存失败');
        }

        // 保存
        $user->idcard_pic = $request->input('idcard_pic');
        $user->biz_lic_pic = $request->input('biz_lic_pic');
        $user->ent_check = 1;
        
        if ($user->save()) {
            return $this->message('提交成功，请等待审核');
        } else {
            return $this->failed('保存失败，请稍后重试');
        }
    }

    /**
     * 后台账号
     */
    public function account(Request $request)
    {
        $manager = $request->user()->shop;

        return view('front.member.account', compact('manager'));
    }

    /**
     * 保存店铺账号密码
     */
    public function accountStore(Request $request)
    {
        $messages = [
            'email.email' => '账号必须是邮箱',
            'password.min' => '密码必须大于六位数'
        ];

        $storeOrm = Shop::where('user_id', Auth::user()->id)->first();

        $validator = Validator::make($request->all(), [
            'email' => [
                'required',
                'string',
                'email',
                Rule::unique('stores')->ignore($storeOrm->id),
                'max:255'
            ],
            'password' => 'required|string|min:6',
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $storeOrm->email = $request->input('email');
        $storeOrm->password = bcrypt($request->input('password'));

        if ($storeOrm->save()) {
            return $this->success('设置成功');
        } else {
            return $this->failed('设置失败');
        }
    }
}
